package com.rk.pethome.basic.controller;
import com.rk.pethome.basic.util.AjaxResult;
import com.rk.pethome.basic.util.FastDfsApiOpr;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FastdfsController {

    @PostMapping
    public AjaxResult upload(MultipartFile file){
        try {
            //获取上传的文件名
            String originalFilename = file.getOriginalFilename();
            //获取文件后缀名
            String extension = FilenameUtils.getExtension(originalFilename);
            //返回FastDfs对应的文件路径
            String uploadPath = FastDfsApiOpr.upload(file.getBytes(), extension);
            return new AjaxResult().setResult(uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            return new AjaxResult(false,e.getMessage());
        }
    }

    /**
     * 参数：完整路径 /goup1/xxxxx/yyyy
     * 返回值：成功与否，还要返回地址
     *
     */
    @DeleteMapping
    public AjaxResult del(@RequestParam(required = true,value = "path")String path){
        String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
        String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
        String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
        System.out.println("删除文件路径"+path);
        FastDfsApiOpr.delete(groupName, remotePath);
        return  new AjaxResult();
    }
}
